package com.example.animaldoctor03;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class JSONArrayAdapter extends BaseAdapter {

	
	private Context ctx;
	private JSONArray jsonArray ;
	private String property ;
	private boolean hasIcon;
	public JSONArrayAdapter(Context ctx , JSONArray jsonArray , String property , boolean hasIcon){
		
		
		this.ctx = ctx ;
		this.jsonArray = jsonArray;
		this.property = property;
		this.hasIcon = hasIcon;
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return jsonArray.length();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return jsonArray.optJSONObject(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		try{
			
			return ((JSONObject)getItem(position)).getInt("id");
		}catch(JSONException e)
		{
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		LinearLayout linear = new LinearLayout(ctx);
		linear.setOrientation(0);
		TextView tv = new TextView(ctx);
		
		try{
			String itemName = ((JSONObject)getItem(position)).getString(property);
			tv.setText(itemName);
		}catch(JSONException e){
			e.printStackTrace();
		}
		tv.setTextSize(20);
		if(hasIcon){
			linear.addView(tv);
			return linear;
			
		}
		else{
			tv.setTextColor(Color.BLUE);
			return tv;
		}
		
	}

}
